package com.blb.controller;

import java.io.File;import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAccount;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.blb.entity.Menu;
import com.blb.entity.Role;
import com.blb.entity.User;
import com.blb.entity.UserExample;
import com.blb.entity.UserExample.Criteria;
import com.blb.entity.Userrole;
import com.blb.mapper.MenuExtMapper;
import com.blb.mapper.UserMapper;
import com.blb.service.UserService;
import com.blb.shiro.PasswordHelper;
import com.blb.utils.DateUtils;
import com.blb.utils.LayuiPage;
import com.blb.utils.NowUserUtils;
import com.blb.utils.UUIDUtils;
import com.mysql.jdbc.StringUtils;

@Controller
@RequestMapping("user")
public class UserController {
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private MenuExtMapper menuExtMapper;
	
	@Autowired
	private UserService userService;

	private static String filePath = "D:/file_upload/";
		
	
	/**
	 *  根据用户id获取它所拥有的按钮
	 * @param model
	 * @param httpsession
	 * @param menuid
	 * @return
	 * @throws IOException
	 */
	@RequiresPermissions("user:list")
	@RequestMapping("showList")
	public String showList(Model model,HttpSession httpsession,@Param("menuid") String menuid) throws IOException{
		//查询左侧菜单
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		List<Menu> list = menuExtMapper.getButtenByuserid(user.getId(),menuid);
		
		model.addAttribute("bts", list);
		return "/user/user_list";
	}
	
	
	
	/**
	 * 用户登录
	 * @param user
	 * @param session
	 * @param model
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("login")
	public String login(String username, String password, HttpSession httpSession, RedirectAttributes model) throws IOException{

		Subject subject = SecurityUtils.getSubject();
		
		UsernamePasswordToken token = new UsernamePasswordToken(username,password);
		try{
			subject.login(token);
			System.out.println("登录成功");
		}catch (UnknownAccountException uae) {
			System.err.println("用户名不存在");
			model.addFlashAttribute("msg", "用户名不存在");
			return "redirect:/";
		} catch (IncorrectCredentialsException ice) {
			System.err.println("密码错误");
			model.addFlashAttribute("msg", "密码错误");
			return "redirect:/";
		} catch (LockedAccountException lae) {
			System.err.println("账号被冻结");
			model.addFlashAttribute("msg", "账号已被冻结");
			return "redirect:/";
		} catch (AuthenticationException ae) {
			ae.printStackTrace();
			System.err.println("其它错误");
			model.addFlashAttribute("msg", "其他错误");
			return "redirect:/";
		}
		
		if(subject.isAuthenticated()){
			if(subject.hasRole("root")){
				System.out.println("11111");
			}
			if(subject.isPermitted("user:list")){
				System.out.println(12312312);
			}
		}
		
		return "redirect:/user/index";
		
	}
	
	
	
	
	
	/**
	 * 首页
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("index")
	public String index(Model model,HttpSession httpsession) throws IOException{
		//查询左侧菜单
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		List<Menu> list = menuExtMapper.getMenusByUserId(user.getId(), "0", "目录");
		
		model.addAttribute("menus", list);
		return "index";
	}
	
	/**
	 * 分页
	 * @param page
	 * @param limit
	 * @param username
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("page")
	public LayuiPage page(int page,int limit,String username) throws IOException{
		LayuiPage pagelist = userService.page((page-1)*limit, limit, username);
		return pagelist;
	}
	
	/**
	 * 显示图片
	 * @param name
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("getImage")
	public ResponseEntity<byte[]> getImage(String name) throws IOException{
		File file = new File(filePath + name);
		HttpHeaders httpHeaders = new HttpHeaders();
		httpHeaders.setContentType(MediaType.IMAGE_JPEG);
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), httpHeaders, HttpStatus.OK);
	}
	
	
	/**
	 * 判断用户名是否存在
	 * @param username
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("isExist")
	public String isExist(String username) throws IOException{
		List<User> list = userService.isExist(username);
		if(!list.isEmpty()){
			return "用户名已存在";
		}
		return "";
	}
	
	
	/**
	 * 添加
	 * @param user
	 * @param httpsession
	 * @throws IOException
	 */
	@RequiresPermissions("user:add")
	@ResponseBody
	@RequestMapping("add")
	public String add(User user,HttpSession httpsession,@Param("roles")String roles) throws IOException{
		PasswordHelper.getPassword(user);
		user.setId(UUIDUtils.getID());
		user.setCreateTime(DateUtils.gettime());
		
		User user1 = NowUserUtils.getNowUser();
		user.setCreateUser(user1.getUsername());
		try {
			String msg = userService.add(user,roles);
			return msg;
		} catch (IOException e) {
			e.printStackTrace();
			return "添加失败"+e.getMessage();
		}
	}
	
	
	
	/**
	 * 修改
	 * @param user
	 * @param httpsession
	 * @return
	 */
	@RequiresPermissions("user:update")
	@ResponseBody
	@RequestMapping("update")
	public String update(User user,HttpSession httpsession,@Param("roles")String roles){
		
		//如果密码不为空则重新设置密码
		if(!StringUtils.isNullOrEmpty(user.getPassword())){
			PasswordHelper.getPassword(user);
		}else{
			user.setPassword(null);
		}
		
		user.setState(user.getState()==null?-1:1);
		user.setUpdateTime(DateUtils.gettime());
		
		User user1 = NowUserUtils.getNowUser();
		user.setUpdateUser(user1.getUsername());
		
		
		try { 
			userService.update(user,roles);
		} catch (IOException e) {
			e.printStackTrace();
			return "修改失败"+e.getMessage();
		}
		return "";
	}
	
	/**
	 * 删除
	 * @param ids
	 * @return
	 */
	@RequiresPermissions("user:delete")
	@ResponseBody
	@RequestMapping("delete")
	public String delete(@RequestBody List<String> ids){
		String msg = "";
		try {
			msg = userService.delete(ids);
		} catch (IOException e) {
			e.printStackTrace();
			return e.getMessage();
		}
		return msg;
	}
	
	
	
	/**
	 * 跳转添加
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("showAdd")
	public String roleList(Model model) throws IOException{
			List<Role> role = userService.roleNameList();
			model.addAttribute("roles", role);
			return "user/user_add";
	}
	
	
	/**
	 * 跳转修改
	 * @param model
	 * @param user
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("showUpdate")
	public String updateRole(Model model,User user) throws IOException{
		List<Role> role = userService.roleNameList();
		List<Userrole> list = userService.getRoleListByuserid(user);
		String rolelist = "";
		if(!list.isEmpty()){
			rolelist = JSON.toJSON(list).toString();
		}
		model.addAttribute("roles", role);
		model.addAttribute("rolelist", rolelist);
		model.addAttribute("user", user);
		return "user/user_update";
	}
	
	/**
	 * 设置状态
	 * @param state
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("state")
	public String state(@Param("state") boolean state,@Param("id")String id){
		try {
			userService.state(state, id);
			return "";
		} catch (IOException e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}
	
}
